package com.edais.service.imp;

import com.edais.dao.LoanDao;
import com.edais.dao.WxEnjoyDao;
import com.edais.mina.TcpMinaClient;
import com.edais.service.UserService;
import com.edais.service.WxEnjoyService;
import com.edais.util.CommonUtil;
import com.edais.util.JsonUtil;
import com.edais.util.StringUtil;
import com.lb.sssq.dao.DepositDao;
import com.lb.sssq.util.Consts;
import com.lb.sssq.util.Message;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultDTO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service

public class WxEnjoyServiceImp implements WxEnjoyService {
	private static final Log logger = LogFactory.getLog(WxEnjoyServiceImp.class);

	@Autowired
	private LoanDao loanDao;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private DepositDao depositDao;
	
	@Autowired
	private WxEnjoyDao wxEnjoyDao;
	
	
	@Override
	public String buyEnjoyPlan(Map<String, Object> map) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getTurnOutDetail(Map<String, Object> map) throws Exception {
		// TODO Auto-generated method stub
		String transCode = "E390002";
		Map<String,Object> coreMap = new HashMap<String,Object>();
		coreMap.put("userId", map.get("userId"));
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);

		Map<String,Object> rtnMap=new HashMap<String,Object>();
		if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			String[] keys={
//					"handChargeRate", //手续费百分比
					"turnOutMsg", //转出小提示（文字描述）
					"enableAmount", //可转出总金额
					"curBondAmount", //在投债券总价值
					"matchAmount", //撮合中金额
//					"minHandCharge", //最小手续费
//					"couponNum",  //可用手续费券的数量
					"inAmount",	//转入金额
					"outAmount"	//转出金额
			};
			if(jsonArr != null && jsonArr.size() > 0){
				JSONObject jsonObj = jsonArr.getJSONObject(0);
				for (int i = 0; i < keys.length; i++) {
					if(jsonObj.containsKey(keys[i])){
						rtnMap.put(keys[i], jsonObj.getString(keys[i]));
					}else{
						rtnMap.put(keys[i], "");
					}
				}
//				rtnMap.put("minHandCharge", userService.getSysSettingHtmlInfo("ysjs_zxsxf_value"));//最小手续费
//				rtnMap.put("totalNum", 1);
			}else{
				for (int i = 0; i < keys.length; i++) {
					rtnMap.put(keys[i], "0");
				}
			}
			String ysjsMsg=userService.getSysSettingHtmlInfo("ysjs_zc_msg");
			ysjsMsg=ysjsMsg.replaceAll("\"","'");
			rtnMap.put("turnOutMsg", ysjsMsg);
			// 设置返回code
			ResultDTO<Map> resultDTO = new ResultDTO<>(ResultCode.SUCCESS);
			resultDTO.setRecord(rtnMap);
			String result = resultDTO.toJsonString();
			try {
				result = result.replaceAll("\\\\","");
				System.out.println("======================="+result);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				
				e.printStackTrace();
			}
			return result;
		}else {
			logger.error("=====核心接口调用异常=====");
			logger.error("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			return new ResultDTO<>(ResultCode.FAILED,Message.CnDescriptionExpression.BUSINESSE_ERROR).toJsonString();
		}
	}

	/**
	 * 转出接口
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public String updateInvestmentAmount(Map<String, String> map) throws Exception{
		
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		/**
		 * 调用核心接口 E390010转出操作
		 * */
		String transCode = "E390010";//转出优享计划
		Map<String, Object> queryCoreMap = new HashMap<String,Object>();
		queryCoreMap.put("userId", map.get("userId"));
		queryCoreMap.put("turnOutAmount", map.get("turnOutAmount"));
		queryCoreMap.put("planId", map.get("planId"));
		map.remove("passwordCash");
		logger.info("转出操作map:"+map.toString());
		
		String limit_amount="0.00";//门槛
		String label_flag="";//
		String amount="0.00";
//		String font_turnOutFee=String.valueOf(map.get("turnOutFee"));//前端传过来的手续费
//		if(!StringUtil.isEmpty((map.get("helpId")))){
//			 Map<String, Object> couponMap = wxEnjoyDao.getPoundageCouponById(Integer.parseInt(map.get("helpId")));
//			 if(couponMap!=null&&couponMap.size()!=0){
//				 limit_amount=String.valueOf(couponMap.get("LIMIT_AMOUNT"));
//				 label_flag=(String) couponMap.get("LABEL_FLAG");
//				 amount=String.valueOf(couponMap.get("AMOUNT"));
//			 }
//			 if(font_turnOutFee==null||"".equals(font_turnOutFee.trim())||"null".equalsIgnoreCase(font_turnOutFee)){
//				 font_turnOutFee="0";
//			 }
//		}
		
//		Map<String, Object> trunMap=getTrunOutFee(map,label_flag,amount);//计算手续费
//		queryCoreMap.putAll(trunMap);
		
		//通过实际手续费判断抵用券是否可用
//		if(Double.parseDouble((String)trunMap.get("computeOutFee"))<Double.parseDouble(limit_amount)){
//			String rescode = Consts.CHECK_CODE;
//			String resmsg = "手续费抵用券需要满"+limit_amount+"元才能使用！";
//			 logger.error("rescode = " + rescode + " resmsg=" + resmsg);
//			 // 设置返回code
//			 return new ResultDTO<>(ResultCode.FAILED,resmsg).toJsonString();
//		 }
		String jsonStr = CommonUtil.constructJsonStr(transCode, map.get("userId"),
				queryCoreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		if(Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))){
//			try {
//				if(!StringUtil.isEmpty((String)map.get("helpId"))){
//					String computeOutFee=(String)trunMap.get("computeOutFee");//实际手续费
//					if(computeOutFee==null||"".equals(computeOutFee.trim())){
//						computeOutFee="0";
//					}
//					if(Double.parseDouble(computeOutFee)>0){
//						int f=wxEnjoyDao.updatePoundageCoupon(Integer.parseInt(map.get("helpId")));
//						logger.info("手续费抵用券是否更新成功:"+f);
//					}
//				}
//
//			} catch (Exception e) {
//				// TODO: handle exception
//				logger.error("手续费抵用券更新发生异常！",e);
//			}
			// 设置返回code
			ResultDTO<Map> resultDTO = new ResultDTO<>(ResultCode.SUCCESS);
			return resultDTO.toJsonString();
		} else {
			String rescode = Consts.ERROR_CODE;
			String resmsg = Message.CnDescriptionExpression.EXIT_AMOUNT_FAILED;
			
			if("run.time.error".equals(jsonObject.get("resmsg"))){
				rescode = Consts.CHECK_CODE;
				resmsg = Message.CnDescriptionExpression.EXIT_AMOUNT_FAILED_TIME;
			}else if("orderValue.is.not.enough".equals(jsonObject.get("resmsg"))){
				rescode = Consts.CHECK_CODE;
				resmsg = Message.CnDescriptionExpression.EXIT_AMOUNT_FAILED_MONEY;
			}else if("single.day.out.limit".equals(jsonObject.get("resmsg"))){
				rescode = Consts.CHECK_CODE;
				resmsg = Message.CnDescriptionExpression.EXIT_AMOUNT_FAILED_SINGLEDAY;
			}else if("single.transfer.limit".equals(jsonObject.get("resmsg"))){
				rescode = Consts.CHECK_CODE;
				resmsg = Message.CnDescriptionExpression.EXIT_AMOUNT_FAILED_SINGLETRANSFER;
			}else if("single.minimum.transfer.limit".equals(jsonObject.get("resmsg"))){
				rescode = Consts.CHECK_CODE;
				resmsg = Message.CnDescriptionExpression.EXIT_AMOUNT_FAILED_SINGLEMINIMUM;
			}
			logger.error("=====E390010核心接口调用异常=====");
			logger.error("rescode = " + rescode + " resmsg=" + resmsg);
			// 设置返回code
			return new ResultDTO<>(ResultCode.FAILED,resmsg).toJsonString();
		}
	}

	/**
	 * @return
	 * @throws Exception 
	 */
	private Map<String, Object> getTrunOutFee(Map<String, String> map,String label_flag,String amount) throws Exception{
		//手续费计算
		String transCode = "E390002";
		Map<String,Object> coreMap = new HashMap<String,Object>();
		coreMap.put("userId", map.get("userId"));
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);

		Map<String,Object> rtnMap=new HashMap<String,Object>();
		if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			if(jsonArr != null && jsonArr.size() > 0){
				JSONObject jsonObj = jsonArr.getJSONObject(0);
				String[] keys={
						"handChargeRate", //手续费百分比
						"enableAmount", //可转出总金额
						"curBondAmount", //在投债券总价值
						"matchAmount", //撮合中金额
						"minHandCharge", //最小手续费
						"couponNum",  //最小手续费
						"inAmount",	//转入金额
						"outAmount"	//转出金额
				};
				for (int i = 0; i < keys.length; i++) {
					if(jsonObj.containsKey(keys[i])){
						rtnMap.put(keys[i], jsonObj.getString(keys[i]));
					}else{
						rtnMap.put(keys[i], "0");
					}
				}
			}
		}
		String trunOutFee="0";//手续费
		String inAmount=(String)rtnMap.get("inAmount");
		if(Double.parseDouble(map.get("turnOutAmount"))>Double.parseDouble(inAmount)){
			BigDecimal b1=new BigDecimal(map.get("turnOutAmount"));
			BigDecimal b2=b1.subtract(new BigDecimal(inAmount));
			BigDecimal b3=b2.multiply(new BigDecimal((String)rtnMap.get("handChargeRate")));
			BigDecimal b4=b3.divide(new BigDecimal(100));
			trunOutFee=String.valueOf(b4);
		}
		System.out.println("计算后的手续费:"+trunOutFee);
		logger.info("计算后的手续费:"+trunOutFee);
		String couponAm="0";
		Map<String, Object> resMap=new HashMap<String,Object>();
		resMap.put("computeOutFee", trunOutFee);
		if(!StringUtil.isEmpty(map.get("helpId"))){
			//如果是全免，手续费全部抵扣,否则取抵用券金额
			if("1".equals(label_flag) && !StringUtils.isBlank(amount)){
				couponAm=amount;
			}else{
				//如果是全免，手续费直接设置为0
				resMap.put("turnOutFee", "0");
				resMap.put("turnOutRate", (String)rtnMap.get("handChargeRate")==null?"0":(String)rtnMap.get("handChargeRate"));
				return resMap;
			}
		}
		System.out.println("+++++++++couponAm:"+trunOutFee);
		logger.info("couponAm:"+couponAm);
		if(Double.parseDouble(trunOutFee)!=0 && Double.parseDouble(couponAm)!=0){
			if(Double.parseDouble(trunOutFee)<Double.parseDouble(couponAm)){
				trunOutFee="0";//如果券的金额大于手续费,则手续费为0
			}else{
				BigDecimal b5=new BigDecimal(trunOutFee);
				BigDecimal b6=b5.subtract(new BigDecimal(couponAm));
				trunOutFee=String.valueOf(b6);
				System.out.println("券抵扣后的手续费:"+String.valueOf(b6));
				logger.info("券抵扣后的手续费:"+String.valueOf(b6));
			}
		}
		System.out.println("最后实际扣除的手续费:"+trunOutFee);
		logger.info("最后实际扣除的手续费:"+trunOutFee);
		resMap.put("turnOutFee", trunOutFee);
		resMap.put("turnOutRate", (String)rtnMap.get("handChargeRate")==null?"0":(String)rtnMap.get("handChargeRate"));
		return resMap;
	}
	
	@Override
	public Map dealBuyDepositGetByBalance(Map<String, Object> pageMode)
			throws Exception {
		Map<String, Object> retMap = null;
		if(pageMode == null){
			return retMap;
		}
		retMap = new HashMap<String,Object>();
		
		// 购买优享计划E390011
		Map<String,Object> resMap = buyDepositGet(pageMode);
		if (resMap == null || !"00000".equals(resMap.get("rescode"))) {
			logger.error("余额购买产品异常" + resMap.get("resmsg"));
			retMap.put("rescode", resMap.get("rescode"));
			retMap.put("resmsg", resMap.get("resmsg"));
		}else{
			// 获取优享计划订单号
			String buyOrderId = resMap.get("orderId") + "";
			pageMode.put("buyOrderId", buyOrderId);
			retMap.put("orderId", buyOrderId);
			retMap.put("investAmount", resMap.get("investAmount"));
			retMap.put("rescode", Consts.SUCCESS_CODE);
			retMap.put("resmsg", "购买活期成功");
		}

		return retMap;
	}
	
	public  Map<String,Object> buyDepositGet(Map<String,Object> map) throws Exception{
		if(map == null || map.size() == 0){
			return null;
		}
		
		String transCode = "E390011";
		
		String userId = (null == map.get("userId") ? "" : (String)map.get("userId"));
		String buyAmount = (null == map.get("investmentAmount") ? "" : (String)map.get("investmentAmount"));
		String planId = (null == map.get("financeId") ? "" : (String)map.get("financeId"));
		String cycleMatchType = (null == map.get("cycleMatchType") ? "" : (String)map.get("cycleMatchType"));
		
		// 设置报文体报文数据
		Map<String, Object> pageModel = new HashMap<String, Object>();
		pageModel.put("userId", userId);
		pageModel.put("investmentAmount", buyAmount);// 购买金额
		pageModel.put("currency", "CNY");// 货币单位:CNY人民币，USD美元
		pageModel.put("financeId", planId);// 产品类型
		pageModel.put("cyclematchtype", cycleMatchType);// 资金流转方式：1--收益循环投资—本息循环；2—收益每月返还—本金循环3—不循环
		pageModel.put("buyMedia", "2");//购买媒介:1.网站；2.手机
		
		Map resmap = coreUse(userId, transCode, pageModel);
		return resmap;
		
	}
	/**
	 * 调用核心接口
	 * 
	 * */
	@Transactional
	public Map coreUse(String userId,String transCode,Map<String, Object> pageModel) throws Exception {
		// 设置报文体报文数据
		String jsonStr = CommonUtil.constructJsonStr(transCode, userId, pageModel);// 构建json字符串
		TcpMinaClient tcpMinaClient = new TcpMinaClient();
		String rtnStr = tcpMinaClient.sendMessage(jsonStr);

		if(StringUtils.isBlank(rtnStr)){
			logger.error("调用核心接口发生异常" + ",接口id：" + transCode);
			throw new Exception("调用核心接口发生异常" + ",接口id：" + transCode);
		}
		
		rtnStr = rtnStr.substring(8, rtnStr.length());
		// 转化json数据为页面模型数据格式
		Map rtnMap = (HashMap) JsonUtil.getObjectFromJsonString(rtnStr,
				HashMap.class);

		return rtnMap;
	}

	@Override
	public Map<String,String> getAcctDebtCDetails(Map<String, Object> accMap)
			throws Exception {
		// TODO Auto-generated method stub
		String transCode = "E390013";
		Map<String,Object> coreMap = new HashMap<String,Object>();
		coreMap.put("userId", accMap.get("userId"));
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, coreMap);
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);

		Map<String,String> rtnMap=new HashMap<String,String>();
		if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			if(jsonArr != null && jsonArr.size() > 0){
				JSONObject jsonObj = jsonArr.getJSONObject(0);
				String[] keys={
						"id",//--id
						"bidId",//标的ID
						"orderId",//--订单ID
						"loanMonths",//--标的天数
						"agreementNo",//-- 优享计划合同模块编号 -->
						"assetNo",//-- 优享计划资产包编号 -->
						"investAmount",//--投资金额
						"investAmount",//--投资金额
						"interest",//--年利率
						"investPeriod",//--投资期限
						"userId",//--用户ID
						"investDate"//--起息日期
				};
				for (int i = 0; i < keys.length; i++) {
					if(jsonObj.containsKey(keys[i])){
						rtnMap.put(keys[i], jsonObj.getString(keys[i]));
					}else{
						rtnMap.put(keys[i], "");
					}
				}
			}
		}else {
			logger.debug("=====核心接口调用异常=====");
			logger.debug("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
		}
		return rtnMap;
	}
	
	

	
}
